package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{

	@Autowired
	CustomerRepository customerRepository;
	
	// 查询所有未关联客户列表
	@Override
	public List<Customer> findNoAssociationCustomers() {
		return customerRepository.findByFixedAreaIdIsNull();
	}

	// 已经关联到指定定区的客户列表
	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	// 将客户关联到定区上 ， 将所有客户id 拼成字符串 1,2,3，使用@QueryParam实现
	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
		// 第一步：根据传递的地区ID，将对应的字段置null
		customerRepository.clearFixedAreaId(fixedAreaId);
		if(StringUtils.isBlank(customerIdStr)){
			return; // 如果没有传递客户ID，就返回
		}
		// 第二步：将客户ID使用逗号分隔，获取客户ID，将客户ID，重新和定区ID进行关联
		if(!"null".equals(customerIdStr)){
			String[] customerIds = customerIdStr.split(",");
			for(String customerId:customerIds){
				customerRepository.updateFixedAreaId(Integer.parseInt(customerId),fixedAreaId);
			}
		}
		
	}
//注册
	@Override
	public void regist(Customer customer) {
		// TODO Auto-generated method stub
		customerRepository.save(customer);
	}
//根据电话查用户
	@Override
	public Customer findByTelephone(String telephone) {
		return  customerRepository.findByTelephone(telephone);
	}
//修改绑定状态
	@Override
	public void updateType(String telephone) {
		// TODO Auto-generated method stub
		customerRepository.updateType(telephone);
	}

}
